package com.hk.yajin.function.members.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hk.developmentlib.baseben.NewWorkBean;
import com.hk.developmentlib.callback.HttpCallBack;
import com.hk.developmentlib.utills.DeviceUtils;
import com.hk.developmentlib.utills.FastjsonUtils;
import com.hk.developmentlib.utills.UiUtil;
import com.hk.developmentlib.utills.des.Base64;
import com.hk.yajin.R;
import com.hk.yajin.base.BaseActivity;
import com.hk.yajin.manager.UserInfoManager;
import com.hk.yajin.model.UserInfo;
import com.hk.yajin.utills.HttpRequestUtils;
import com.hk.yajin.utills.url.UrlConstants;

import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;

public class UserAdviceActivity extends BaseActivity {

    private Toolbar toolbar;
    private TextView tv_right;
    private LinearLayout lly_image_container;
    private TextView tv_image_count;
    private ImageView iv_addpic;
    private EditText et_advice;
    private TextView tv_count;
    ArrayList<String> selectImages = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_advice);
        initView();

    }

    private void initView() {
        initToolBar(R.string.user_advice);
        tv_image_count = (TextView) findViewById(R.id.tv_image_count);
        lly_image_container = (LinearLayout) findViewById(R.id.lly_image_container);
        iv_addpic = (ImageView) findViewById(R.id.iv_addpic);
        iv_addpic.setOnClickListener(this);
        et_advice = (EditText) findViewById(R.id.et_advice);
        tv_count = (TextView) findViewById(R.id.tv_count);
        et_advice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    tv_count.setText(s.length() + "/200");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    @Override
    protected void initToolBar(int titleId) {
        super.initToolBar(titleId);
        tv_right = (TextView) findViewById(R.id.tv_right);
        tv_right.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_right:
                hideKeyboard(tv_right);
                submitData();
                break;
            case R.id.iv_addpic:
                PhotoPicker.builder()
                        .setPhotoCount(4)
                        .setShowCamera(true)
                        .setShowGif(true)
                        .setSelected(selectImages)
                        .setPreviewEnabled(false)
                        .start(this, PhotoPicker.REQUEST_CODE);
                break;
        }
    }

    private void submitData() {
        String content = et_advice.getText().toString();
        if (TextUtils.isEmpty(content)) {
            showShortToast("反馈内容不能为空");
            return;
        }

        if (isNetWorkConnect()) {
            showLoadingView();
            List<KeyValue> list = new ArrayList<KeyValue>();
            if (selectImages != null && selectImages.size() > 0) {
                for (int i = 0; i < selectImages.size(); i++) {
                    list.add(new KeyValue("img[]", new File(selectImages.get(i))));
                }
            }
            list.add(new KeyValue("content", content));
            list.add(new KeyValue("loginkey", UserInfoManager.getInstance().getLoginkey()));
            MultipartBody body = new MultipartBody(list, "UTF-8");
            RequestParams params = new RequestParams(UrlConstants.FUNCTION_SUBMIT_ADVICE);
            params.setRequestBody(body);
            params.setMultipart(true);

            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    if (!TextUtils.isEmpty(result) && result.startsWith("{") && result.endsWith("}")) {
                        NewWorkBean data = FastjsonUtils.getBeanObject(result, NewWorkBean.class);
                        if (data.getCode() == 0) {
                            showShortToast("提交成功，感谢反馈");
                            finish();
                        } else {
                            showShortToast(data.getMsg());
                        }
                    } else {
                        showShortToast("服务器返回异常");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    LogUtil.d("ex:" + ex.getMessage());
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideLoadingView();
                }

            });


//            showLoadingView();
//            Map<String, Object> reqParam = UserInfoManager.getUserKeyMapIfLogin();
//            reqParam.put("content", content);
//            if (selectImages != null && selectImages.size() > 0) {
//                for (int i = 0; i < selectImages.size(); i++) {
//                    reqParam.put("img[" + i + "]", new File(selectImages.get(i)));
//                }
//            }
//
//            HttpRequestUtils.post(false, UrlConstants.FUNCTION_SUBMIT_ADVICE, reqParam, false, new HttpCallBack() {
//
//                @Override
//                public void onSucced(String data) {
//                    hideLoadingView();
//                    showShortToast("提交成功，感谢反馈");
//                    finish();
//                }
//
//                @Override
//                public void onErrorCode(NewWorkBean bean) {
//                    hideLoadingView();
//                    showShortToast(bean.getMsg());
//                }
//
//                @Override
//                public void onBadHttp(String tip) {
//                    hideLoadingView();
//                    showShortToast(tip);
//                }
//
//            });
        }
    }

    @Override
    protected void onBackPressd() {
        if (TextUtils.isEmpty(et_advice.getText().toString()) && selectImages.size() == 0) {
            finish();
        } else {
            new AlertDialog.Builder(UserAdviceActivity.this).setTitle(R.string.tip)//设置对话框标题
                    .setMessage(R.string.quittip)
                    .setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .setNegativeButton(R.string.cancle, null)
                    .show();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                final ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                if (photos != null && photos.size() > 0)
                    selectImages.clear();
                selectImages.addAll(photos);
                tv_image_count.setText(photos.size() + "/4");
                setImageViews();
            }

        }
    }


    private void setImageViews() {
        lly_image_container.removeAllViews();
        for (int i = 0; i < selectImages.size(); i++) {
            //加载图片
            final int position = i;
            ImageView imageView = addChlidImage(position);
            File file = new File(selectImages.get(i));
            Glide.with(this).load(file).thumbnail(0.1f).into(imageView);

        }
    }

    private ImageView addChlidImage(final int position) {
        ImageView imageview = new ImageView(this);
        imageview.setLayoutParams(new LinearLayout.LayoutParams(0, UiUtil.dip2px(100), 1));
        lly_image_container.addView(imageview);
        imageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhotoPreview.builder()
                        .setPhotos(selectImages)
                        .setCurrentItem(position)
                        .setShowDeleteButton(false)
                        .start(UserAdviceActivity.this);
            }
        });
        return imageview;
    }


}
